package com.haojiang.mh.service.api

import com.haojiang.mh.cache.Const
import com.haojiang.mh.utils.SpUtil
import okhttp3.Interceptor
import okhttp3.Response

/**
 * 所有请求自带Token参数
 */
class TokenInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val oldRequest = chain.request().newBuilder().build()
        return if (SpUtil[Const.TOKEN_LOCAL, ""].isEmpty()) {
            chain.proceed(oldRequest)
        } else {
            val tokenUrlBuilder = oldRequest.url().newBuilder()
                .scheme(oldRequest.url().scheme())
                .host(oldRequest.url().host())
                .addQueryParameter("token", SpUtil[Const.TOKEN_LOCAL, ""])

            val newRequest = oldRequest.newBuilder()
                .method(oldRequest.method(), oldRequest.body())
                .url(tokenUrlBuilder.build())
                .build()
            chain.proceed(newRequest)
        }
    }
}